package cc.rengu.igas.opms.core.service.trans.quickpay;

import cc.rengu.igas.opms.common.dao.BankSupportCfgMapper;
import cc.rengu.igas.opms.common.dao.impl.BankSupportCfgMapperImpl;
import cc.rengu.igas.opms.common.entity.BankSupportCfgInfo;
import cc.rengu.igas.opms.common.enums.RespCodeEnum;
import cc.rengu.igas.opms.common.enums.SignTypeEnum;
import cc.rengu.igas.opms.core.service.base.ManageService;
import cc.rengu.igas.opms.facade.bean.BindCardInfo;
import cc.rengu.igas.opms.facade.request.SignAcctInfoListQueryRequest;
import cc.rengu.igas.opms.facade.response.SignAcctInfoListQueryResponse;
import cc.rengu.igas.share.core.model.BankCodeInfo;
import cc.rengu.igas.share.core.model.UserInfo;
import cc.rengu.igas.share.core.realize.BompService;
import cc.rengu.igas.share.core.realize.UserService;
import cc.rengu.igas.share.core.realize.impl.BompServiceImpl;
import cc.rengu.igas.share.core.realize.impl.UserServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SignAcctInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.SignAcctInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.SignAcctInfo;
import cc.rengu.oltp.service.common.enums.LimitTypeEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.TransLimitInfo;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户绑卡列表查询
 * Created by liujinan on 2020/4/16.
 * modify by wangcheng 2021-09-13
 */
public class SignAcctInfoListQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        SignAcctInfoListQueryRequest signAcctInfoListQueryRequest = new SignAcctInfoListQueryRequest();
        ConvertUtil.convertOutput(signAcctInfoListQueryRequest);
        return signAcctInfoListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        BizResponse<SignAcctInfoListQueryResponse> bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.IGAS);

        SignAcctInfoListQueryRequest signAcctInfoListQueryRequest = (SignAcctInfoListQueryRequest) request;
        //机构标识
        String instId = signAcctInfoListQueryRequest.getHeader().getInstId();
        //用户编号
        String userId = signAcctInfoListQueryRequest.getUserId();

        //step1.用户主体，签约主体，签约类型赋值
        String userInst = instId;
        String signInst = instId;
        if (null != platMchntInfo) {
            if (SignTypeEnum.PLAT_CLASS_SIGN.getSignTypeCode().equals(platMchntInfo.getSignType())) {
                userInst = platMchntInfo.getPlatMchntNo();
                signInst = platMchntInfo.getPlatMchntNo();
            }
        } else {
            rglog.info("请求未上送平台商户号，默认查询银行级签约信息!");
        }

        SignAcctInfoListQueryResponse signAcctInfoListQueryResponse = new SignAcctInfoListQueryResponse();
        rglog.debug("获取用户信息...");
        UserService userService = new UserServiceImpl();
        UserInfo userInfo = userService.getUserInfo(instId, userId, signAcctInfoListQueryRequest.getHeader().getSession());
        //非授信用户，用户信息不存在直接报错
        if (null == userInfo) {
            rglog.error("收银台用户信息不存在！");
            bizResponse.setRespCode(RespCodeEnum.USER_NOT_EXIT_ERROR.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.USER_NOT_EXIT_ERROR.getRespDesc());
            return bizResponse;
        } else {
            if (!"00".equals(userInfo.getUserStatus())) {
                rglog.error("收银台用户已注销或者冻结<{}>", userInfo.getUserStatus());
                bizResponse.setRespCode(RespCodeEnum.USER_STATUS_ABNORMAL.getRespCode());
                bizResponse.setRespDesc(RespCodeEnum.USER_STATUS_ABNORMAL.getRespDesc());
                return bizResponse;
            }

            //根据支付密码是否为空赋值支付密码标志字段（passwordFlag）
            rglog.debug("用户密码字段是否为空:userTransPassword:<{}>", userInfo.getTransPassword());
            if (StringUtil.isEmptyOrNull(userInfo.getTransPassword())) {
                signAcctInfoListQueryResponse.setPasswordFlag(AppParamConstant.NO);
            } else {
                signAcctInfoListQueryResponse.setPasswordFlag(AppParamConstant.YES);
            }

            //根据 用户编号/签约主体 获取列表
            rglog.debug("获取绑卡列表信息...");
            SignAcctInfoMapper signAcctInfoMapper = new SignAcctInfoMapperImpl();
            List<SignAcctInfo> signAcctInfoList = signAcctInfoMapper.selectSignAcctInfoBySignTyUserId(instId, userId, signInst);
            //判断绑卡列表信息是否为空
            if (null != signAcctInfoList && !signAcctInfoList.isEmpty()) {
                signAcctInfoList = signAcctInfoList.stream().filter(item -> AppParamConstant.YES.equals(item.getSignStatus()))
                        .sorted(Comparator.comparing(SignAcctInfo::getPayIndex)).collect(Collectors.toList());
                if (!signAcctInfoList.isEmpty()) {
                    rglog.info("用户存在签约信息,userId:<{}>,signInst:<{}>", userId, signInst);
                    //转换应答实体
                    List<BindCardInfo> bindCardInfoList = convertBindCardInfoInfo(signAcctInfoList, signAcctInfoListQueryRequest, userInst);
                    signAcctInfoListQueryResponse.setBindCardList(bindCardInfoList);
                }
            }
        }
        bizResponse.setResult(signAcctInfoListQueryResponse);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        SignAcctInfoListQueryResponse signAcctInfoListQueryResponse = (SignAcctInfoListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(signAcctInfoListQueryResponse);
    }

    /**
     * 查询的数据库实体类转换为结果响应类
     * Created by liujinan on 2020/4/16.
     */
    private ArrayList<BindCardInfo> convertBindCardInfoInfo(List<SignAcctInfo> signAcctInfos, SignAcctInfoListQueryRequest request, String userInst) throws Exception {
        //查询用户限额限次信息获取用户 单笔限额和单日限额数据信息
        rglog.info("获取用户限额限次数据实体中单笔限额和单日限额，若不存在默认为:0.00");
        UserService userService = new UserServiceImpl();
        TransLimitInfo transLimitInfo = userService.getUserLimitCfgInfo(request.getHeader().getInstId(), request.getUserId(), userInst, LimitTypeEnum.CASHIER.getLimitType());
        if (null == transLimitInfo) {
            rglog.debug("用户限额未配置获取机构的默认限额信息..");
            transLimitInfo = userService.getUserLimitCfgInfo(request.getHeader().getInstId(), AppParamConstant.DEFAULT_INSTID, AppParamConstant.DEFAULT_INSTID, LimitTypeEnum.CASHIER.getLimitType());
            if (null == transLimitInfo) {
                rglog.error("机构:<{}>未配置默认限额信息", request.getHeader().getInstId());
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
        }

        //初始化用户单笔限额和单日限额数据
        String singleLimitAmt = transLimitInfo.getSingleLimitMaxAmt();
        String dateLimitAmt = transLimitInfo.getDayLimitAmt();

        ArrayList<BindCardInfo> bindCardInfos = new ArrayList<>();
        BompService bompService = new BompServiceImpl();
        BankSupportCfgMapper bankSupportCfgMapper = new BankSupportCfgMapperImpl();
        for (SignAcctInfo signAcctInfo : signAcctInfos) {
            //查找支持银行列表配置表获取银行名称-银行名称即银行的简称,获取银行logo的url
            String bankLogo = "";
            String bankName = signAcctInfo.getSignBankName();
            BankCodeInfo bankCodeInfo = bompService.getBankCodeInfoByBandBranchCode(signAcctInfo.getSignBankNo());
            if (null != bankCodeInfo) {
                List<BankSupportCfgInfo> bankSupportCfgInfos = bankSupportCfgMapper.selectOpmsBankSupportCfgByInstIdBankNo(signAcctInfo.getInstId(), bankCodeInfo.getCupsInstId());
                if (null != bankSupportCfgInfos && bankSupportCfgInfos.size() != 0) {
                    bankName = bankSupportCfgInfos.get(0).getBankName();
                    bankLogo = bankSupportCfgInfos.get(0).getBankLogoUrl();
                }
            }

            BindCardInfo bindCardInfo = new BindCardInfo();
            //签约协议号
            bindCardInfo.setSignToken(signAcctInfo.getSignToken());
            //签约类型
            bindCardInfo.setSignType(signAcctInfo.getSignTokenType());
            //签约账户类型
            bindCardInfo.setSignAcctType(signAcctInfo.getSignAcctType());
            //签约银行账号
            bindCardInfo.setSignAcctNo(signAcctInfo.getSignAcctNo());
            //证件类型
            bindCardInfo.setCertType(signAcctInfo.getCertType());
            //证件号码
            bindCardInfo.setCertNo(signAcctInfo.getCertNo());
            //持卡人姓名
            bindCardInfo.setCardHoldName(signAcctInfo.getCardHoldName());
            //预留手机号
            bindCardInfo.setPhoneNo(signAcctInfo.getReserveMobileNo());
            //签约发卡行行号
            bindCardInfo.setSignBankNo(signAcctInfo.getSignBankNo());
            //签约发卡行名称
            bindCardInfo.setSignBankName(bankName);
            //扣款顺序号
            bindCardInfo.setPayIndex(String.valueOf(signAcctInfo.getPayIndex()));
            //单笔限额
            bindCardInfo.setSingleLimitAmt(singleLimitAmt);
            //当日累计限额
            bindCardInfo.setDayLimitAmt(dateLimitAmt);
            //银行logo路径
            bindCardInfo.setBankLogoUrl(bankLogo);
            //小额免密限额
            bindCardInfo.setNoPasswordAmt(signAcctInfo.getNoPasswordAmt());
            //认证限额
            bindCardInfo.setAuthLimitAmt(signAcctInfo.getAuthLimitAmt());
            bindCardInfos.add(bindCardInfo);
        }

        return bindCardInfos;
    }
}
